<template>
    <div class="rt-container">
        <div class="rt-table">
            <table v-if="dataValue" class="el-table el-table--border" align="center">
                <tbody>
                    <tr>
                        <td width="100" />
                        <td v-for="(col,index) in table.columns" :key="index">
                            {{ col.label }}
                        </td>
                    </tr>
                    <tr v-for="(row,rIndex) in table.rows" :key="rIndex">
                        <td>
                            {{ row.label }}
                        </td>
                        <td v-for="(col,cIndex) in table.columns" :key="cIndex" width="100">
                            <el-input v-model="dataValue[row.id][col.id]" @input.native="handleChange($event,rIndex,cIndex)" />
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script>
import mixin from '../mixin'

export default {
    name: 'MatrixInput',
    mixins: [mixin],
    props: {
        table: {
            type: Object,
            default: () => {}
        },
        value: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        return {
            dataValue: [],
            val: {}
        }
    },
    watch: {
        table: {
            handler(value) {
                this.initValue()
            },
            deep: true
        }, value: {
            handler(value) {
                this.initValue()
            }
        }
    },
    created() {
        this.initValue()
    },
    methods: {
        // 初始化矩阵value为二维数组
        initValue() {
            let initValue = {}
            this.table.rows.forEach(row => {
                initValue[row.id] = {}
                this.table.columns.forEach(col => {
                    if (this.value[row.id] && this.value[row.id][col.id]) {
                        initValue[row.id][col.id] = this.value[row.id][col.id]
                    } else {
                        initValue[row.id][col.id] = null
                    }
                })
            })
            this.dataValue = initValue
        },
        handleChange() {
            this.val = this.dataValue
            this.$emit('input', this.val)
            this.$emit('change', this.val)
        }
    }
}
</script>

<style lang="scss" scoped>
.rt-container {
  padding: 20px;
  overflow-x: auto;
  overflow-y: hidden;
  width: 100%;

  .rt-table {
    width: 750px;
  }

  th, td {
    text-align: center;
    vertical-align: middle !important;
  }

  .el-input {
    width: 70%;
  }
}

</style>
